package com.pushdemo.logic;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;

import com.foss.push.app.PushApplication;
//import com.foreveross.chameleon.config.BroadcastConstans;
//import com.foreveross.chameleon.config.DeviceInfoUtil;
////import com.foreveross.chameleon.config.GeneralUtils;
//import com.foss.push.config.PushConstants;
//import com.foss.push.socket.SocketSetupCallback;
//import com.foss.push.utils.GeneralUtils;
//import com.foreveross.chameleon.config.Preferences;
//import com.foreveross.push.nodeclient.PackageUtil;
//import com.foreveross.push.socket.AuthMessageEntity;
//import com.foss.push.socket.PushRTx;
//import com.foss.push.socket.PushSetup;
//import com.foss.push.socket.SocketConnect;
//import com.foreveross.push.socket.TokenGetter;
//import com.foreveross.push.socket.TokenValidator;
import com.pushdemo.config.ChameleonConstants;
import com.foss.push.socket.SocketConnect.SocketMsgHandler;
import org.json.JSONException;
import org.json.JSONObject;
import org.msgpack.MessagePack;
import org.msgpack.type.Value;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by zhouzhineng on 14-8-21.
 * 变色龙心跳委托类
 */
public class ChameleonRegisterDelegate {

    public final static String TAG = "ChameleonHeartbeatDelegate";
    //public static boolean isRegSucc = false;                    //注册步骤是否完成
   /* private static final int HEARTBEAT_CYCLE = 5 * 60 * 1000;//定时任务时间间隔
    private static final int MAX_HEART_TRY_TIME = 3;//心跳最大尝试次数

    private static int countHeartSend = 0;
    private static int countHeartResp = 0;

    private static SocketConnect socket;
    private static SocketConnect currPushSocket = null;
    // token 注册 socket 成功后,连接socket服务器
    private static String currUserName;
    private static ChameleonRegCallback chameleonRegCallback;

    public interface ChameleonRegCallback{
        public boolean isRegSucc(boolean result,String param);
    }

    public static void setChameleonRegCallback(ChameleonRegCallback regCallback) {
        chameleonRegCallback = regCallback;
    }

    public static void getToken() {
        // 检测token -> 获取token
        new TokenGetter().getToken(new TokenGetter.OnTokenGetted() {
            @Override
            public void tokenGetted(String token, String userName) {
                currUserName = userName;
                if(null == token || "".equals(token)) {
                    Log.e(TAG,"push 获取token失败");
                    stopRtx();
                } else {
                    onTokenGetSucc(token);
                }
            }
        });
    }
    // 获取有效【非空，非过期】token后的流程
    private static void onTokenGetSucc(final String token) {
        //AppLog.i("获取token成功 - > 验证token");
        Log.d(TAG,"onTokenGetSucc-->TOKEN "+ token);
        new TokenValidator().register(token, new TokenValidator.OnRegResult() {
            @Override
            public void handleRegResult(boolean isSucc, final String value) {

                Log.d(TAG,"onTokenGetSucc---->" + value);
                if(chameleonRegCallback != null) {
                    chameleonRegCallback.isRegSucc(isSucc,token);
                }
            }
        });
    }

    public static void onRegisterFail() {
        stopRtx();
    }

    public static void onRegisterSucc(SocketConnect s,final String token, String value) {
        Log.d(TAG,"onRegisterSucc--->");
        //currPushSocket = s;
        //socket = s;
        //sendEntity(token);  //变色龙后台只有验证了token信息之后才能交互
        startRtx(s,token);
    }

    public static void stopRtx() {
        if(socket != null) {
            countHeartSend = 0;
            countHeartResp = 0;
            heartSendTime.clear();
            stopTimerHeartBeat();
            socket = null;
            if(currPushSocket != null) {
                currPushSocket.disConnect();
                currPushSocket = null;
            }
        }
    }


    // 开始收发:首先发送一个对象，收到回复后，发送心跳
    public static void startRtx(SocketConnect s, String token) {
        stopRtx();
        //
        socket = s;
        s.setSocketMsgHandler(msgHandler);
        sendEntity(token);
    }

    private static void sendEntity(String token) {
        AuthMessageEntity entity = new AuthMessageEntity();
        entity.setDeviceId(DeviceInfoUtil.getDeviceId());
        entity.setPushToken(token);
        String username = Preferences.getUserName();
        if(username == null || username.equals("")) {
            username = "guest";
        }
        Log.d(TAG,"device id == " + DeviceInfoUtil.getDeviceId());
        Log.d(TAG,"username == " + username);
        Log.d(TAG,"token id == " + token);

        entity.setUserName(username);
        try {
            byte[] msg = PackageUtil.ToByte(entity);
            //AppLog.i("socket 发送对象");
            socket.sendMsg(msg);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }


    // 收到消息，统一处理 入口
    public static SocketMsgHandler msgHandler = new SocketMsgHandler() {
        @Override
        public void onReceiveMsg(byte[] msg) {
            Log.i(TAG,"收到 socket 信息---->" + new String(msg));
            // TODO:处理数据入口
            if(isHeartReply(com.foreveross.chameleon.config.GeneralUtils.copyBytes(msg))) {
                Log.d("PushPlugin","是 心跳包");
                handleMsgHeartReply();
                return;
            }

            // 是否entity reply,
            Object entityReply = getEntityReply(com.foreveross.chameleon.config.GeneralUtils.copyBytes(msg));
            if(entityReply != null) {
                handleEntityReply((Boolean) entityReply);
                return;
            }

            // 常规 push信息
            Log.d("PushPlugin","普通 push信息");
            handleNormalMsg(msg);
        }
    };
     // 是否 entity的回应,如果是，则返回内容，不是则返回null

    private static Object getEntityReply(byte[] bytes) {
        try {
            Value v = PackageUtil.byteToObject(bytes);
            JSONObject jsonObj = new JSONObject(v.toString());
            boolean r = jsonObj.getBoolean("result");
            return r;
        } catch(JSONException e) {
            // 不需要处理,这个数据不是 entity的回复
        }
        return null;
    }

    // 普通消息，先解析成JSON,再处理
    private static void handleNormalMsg(byte[] bytes) {
        try {
            Value v = PackageUtil.byteToObject(bytes);
            String msg = v.toString();
            JSONObject jsonObj = new JSONObject(v.toString());
            Log.d(TAG,"*****接收到的消息---->***" + msg);
            Context context = PushApplication.getApplication();
            Intent it = new Intent();
            it.setAction(PushConstants.ACTION_REC_MESSAGE);
            it.putExtra("msg",msg);
            context.sendBroadcast(it);

        } catch(JSONException e) {
            Log.e("PushPlugin","非心跳，push数据无法解析成json");// 格式错误
        }
    }

    // 定时器发送的 intent
    private static PendingIntent timerIntent;
    private static PendingIntent getTimerIntent() {
        if(timerIntent == null) {
            //Context context = ChameleonApplication.getApplication();
            Context context = PushApplication.getApplication();
            Intent intent = new Intent(context, SendHeartbeatReceiver.class);
            intent.setAction("heartbeat.receiver");
            timerIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
        return timerIntent;
    }

    // 心跳得到回应
    private static void handleMsgHeartReply() {
        countHeartResp++;
        Log.i("PushPlugin", "发送心跳次数 =" + countHeartSend + ", 收到心跳回复 =" + countHeartResp);
        heartSendTime.clear();
    }

    // 处理entity 回应 ， isTrue 响应的 result = isTrue
    private static void handleEntityReply(boolean isTrue) {
        if(isTrue) { // 响应正确
            startTimerHeartBeat();
        } else {// 响应错误,表明上送数据不正确，清理token
            Log.d(TAG,"handleEntityReply--->"+isTrue);
            TokenGetter.clearCurrToken();
            stopRtx();
            PushSetup.getInstance().socketRTxErr();
        }
    }


    // 启动定时任务:心跳
    private static void startTimerHeartBeat() {
        //AppLog.i("启动心跳:startTimerHeartBeat");
        Context context = PushApplication.getApplication();
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime(), HEARTBEAT_CYCLE, getTimerIntent());
    }

    // 结束定时任务:心跳
    private static void stopTimerHeartBeat() {
        //AppLog.i("停止心跳:stopTimerHeartBeat");
        Context context = PushApplication.getApplication();
        if(timerIntent != null) {
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.cancel(timerIntent);
            timerIntent = null;
        }
    }

    // 单次心跳发送
    private static void heartOneTime() {
        if(heartSendTime.size() >= MAX_HEART_TRY_TIME) {// 已经有超过失败限额
            stopRtx();
            PushSetup.getInstance().socketRTxErr();
        } else {
            if(socket != null && socket.isAvailiable()) {
                // 增加一条心跳发送记录，该记录等待回应
                heartSendTime.add(SystemClock.currentThreadTimeMillis());
                byte[] heartSend = PackageUtil.ToByteNoJson("");
                socket.sendMsg(heartSend);
                countHeartSend++;
            } else {
                // socket已经无效了
                stopRtx();
                PushSetup.getInstance().socketRTxErr();
            }
        }
    }
    // 未响应的心跳记录，如果响应了，则清零
    private static ArrayList<Long> heartSendTime = new ArrayList<Long>();


    // 定时器发送的 心跳广播,收到心跳广播后，发送心跳
    public static class SendHeartbeatReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //AppLog.d("SendHeartbeatReceiver::AlarmReceiver 收到广播 from Alarmer");
            heartOneTime();
        }
    }

    // 判断是否为心跳回执
    public static boolean isHeartReply(byte[] btyes) {
        // 生成正确的心跳回应,
        byte[] right = {};
        try {
            byte b = new MessagePack().write("")[0];
            byte[] a = {0, 0, 0, 1, 1, b};
            right = a;
        } catch(IOException e) {
            e.printStackTrace();
        }

        // 比较
        if(btyes.length != right.length) {
            return false;
        }
        for(int i = 0; i < btyes.length; i++) {
            if(btyes[i] != right[i]) {
                return false;
            }
        }
        return true;
    }

*/
}
